package com.coder.rental.security;

import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Resource
    private LoginSucdessHandler loginSuccessHandler; // 注意拼写修正

    @Resource
    private LoginFailHandler loginFailHandler;

    @Resource
    private CustomerAccessDeniedHandler customerAccessDeniedHandler;

    @Resource
    private CustomerAnonymousEntryPoint customerAnonymousEntryPoint;

    @Resource
    private CustomerUserDetailsService customerUserDetailsService;
    @Resource
    private VerifyTokenFilter verifyTokenFilter;

        /**
     * 配置安全过滤链
     *
     * @param http 用于配置HttpSecurity的接口
     * @return 返回构建好的SecurityFilterChain对象
     * @throws Exception 如果配置过程中发生错误，则抛出异常
     */

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        // 登录前过滤
        http.addFilterBefore(verifyTokenFilter, UsernamePasswordAuthenticationFilter.class);
        http
                .formLogin(form -> form
                        .loginProcessingUrl("/rental/user/login") // 设置登录处理URL
                        .successHandler(loginSuccessHandler) // 设置登录成功处理器
                        .failureHandler(loginFailHandler) // 设置登录失败处理器
                )
                .sessionManagement(session -> session // 设置会话管理策略
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                )
                .authorizeHttpRequests(authz -> authz
                        .requestMatchers("/rental/user/login").permitAll() // 允许登录接口匿名访问
                        .anyRequest().authenticated() // 其他请求需认证
                )
                .exceptionHandling(ex -> ex
                        .authenticationEntryPoint(customerAnonymousEntryPoint) // 未认证时入口点
                        .accessDeniedHandler(customerAccessDeniedHandler) // 权限不足处理器
                )
                .cors(cors -> {}) // 启用默认跨域配置
                .csrf(csrf -> csrf.disable()) // 禁用 CSRF
                .userDetailsService(customerUserDetailsService); // 自定义用户详情服务

        return http.build();
    }

}
